<%@ page import="java.util.List" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="com.xpy.entity.Diary" %>
<%@ page import="java.sql.ResultSet" %>
<%@ page import="java.sql.PreparedStatement" %>
<%@ page import="com.xpy.utils.ConnSqlServer" %>
<%@ page import="java.sql.Connection" %>

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>diary</title>
    <link rel="stylesheet" href="css/style2.css">
</head>
<body>
<body>
<%@include file="head.jsp"%>
<div class="diary-container">
    <%
    // 计算页码和每页显示的记录数
        int page;
    page = request.getParameter("page") != null ? Integer.parseInt(request.getParameter("page")) : 1;
    int recordsPerPage = 5;
    int offset = (page - 1) * recordsPerPage;

    // 执行 SQL 查询以获取当前页面的记录
    Connection conn = ConnSqlServer.getConnection();
    PreparedStatement pstm = conn.prepareStatement("select * from diary where id != 1 order by id offset ? rows fetch next ? rows only");
    pstm.setInt(1, offset);
    pstm.setInt(2, recordsPerPage);
    ResultSet rs = pstm.executeQuery();

    // 从结果集中读取数据并显示在页面上
    List<Diary> diaryList = new ArrayList<>();
    while (rs.next()) {
        Diary diary = new Diary();
        diary.setId(rs.getLong("id"));
        diary.setTitle(rs.getString("title"));
        diary.setWdate(rs.getDate("wdate"));
        diaryList.add(diary);
    }

    // 计算总记录数
    PreparedStatement pstm2 = conn.prepareStatement("select count(*) as total from diary where id != 1");
    ResultSet rs2 = pstm2.executeQuery();
    rs2.next();
    int totalRecords = rs2.getInt("total");

    // 计算总页数
    int totalPages = (int) Math.ceil((double) totalRecords / recordsPerPage);
%>

<%-- 显示分页数据 --%>
<table>
    <% for (Diary diary : diaryList) { %>
    <tr>
        <td><%= diary.getId() %></td>
        <td><%= diary.getTitle() %></td>
        <td><%= diary.getWdate() %></td>
    </tr>
    <% } %>
</table>
<div class="pagination">
    <% if (page > 1) { %>
    <a href="?page=<%= page - 1 %>">上一页</a>
    <% } %>

    <% for (int i = 1; i <= totalPages; i++) { %>
    <a href="?page=<%= i %>"><%= i %></a>
    <% } %>

    <% if (page < totalPages) { %>
    <a href="?page=<%= page + 1 %>">下一页</a>
    <% } %>
</div>
</div>

</body>
</html>